package com.aep.ProjetoAnalise;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.widget.AdapterView.OnItemClickListener;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Christian
 * Date: 09/05/13
 * Time: 20:30
 * To change this template use File | Settings | File Templates.
 * Fará o pedido pelo Feed e o mostrará na tela
 */
public class NoticiasActivity extends Activity implements OnItemClickListener {

    public final String tag = "RSSReader";
    private RSSFeed feed = null;
    //private List<RSSItem> comboitems = null;
    private String nome;
    private List<RSSItem> comboitems;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.noticias_layout);
        ArrayList<String> fontes = this.getIntent().getStringArrayListExtra("fontes");
        nome = this.getIntent().getStringExtra("nome");
        new ParseFonts().execute(fontes);
    }
    private class ParseFonts extends AsyncTask<ArrayList<String>, Void, List<RSSItem>>{
        ProgressDialog dialog;
        protected void onPreExecute(){
            dialog = new ProgressDialog(NoticiasActivity.this);
            dialog.setMessage("Loading...");
            dialog.setIndeterminate(true);
            dialog.show();
        }
        @Override
        protected List<RSSItem> doInBackground(ArrayList<String>... param) {
            ArrayList<String> fontes = param[0];
            comboitems = null;
            for (int i = 0; i < fontes.size(); i++){
                //Inicializa o Feed
                feed = getFeed(fontes.get(i));
                //Preenche a lista de itens
                if(comboitems == null){
                    comboitems = feed.getAllItems();
                }else{
                    comboitems.addAll(feed.getAllItems());
                }
            }
            //Organiza as notícias por data
            Collections.sort(comboitems);
            return comboitems;
        }
        protected void onPostExecute(List<RSSItem> comboitems){
            dialog.dismiss();
            //Atualiza a Tela
            updateDisplay(comboitems);
        }
    }
    private RSSFeed getFeed(String urlToRssFeed)
    {
        try
        {
            // configura a URL do Feed
            URL url = new URL(urlToRssFeed);

            // fábrica do SAXParser
            SAXParserFactory factory = SAXParserFactory.newInstance();
            // cria o manipulador SAX do XML
            SAXParser parser = factory.newSAXParser();

            // cria o leitor do XML (scanner)
            XMLReader xmlreader = parser.getXMLReader();
            // instancia o manipulador do RSS
            RSSHandler theRssHandler = new RSSHandler();
            // "Setta" o SAXParser para o manipulador
            xmlreader.setContentHandler(theRssHandler);
            // Fluxo de dados a serem manipulados
            InputSource is = new InputSource(url.openStream());
            // Realiza o "parse"
            xmlreader.parse(is);
            // retorna os resultados no formato de um objeto Feed populado
            return theRssHandler.getFeed();
        }
        catch (Exception ee)
        {
            // caso não consiga capturar o feed, retorne NULL
            return null;
        }
    }

    private void updateDisplay(List<RSSItem> comboitems)
    {
        TextView feedtitle = (TextView) findViewById(R.id.feedtitle);
        ListView itemlist = (ListView) findViewById(R.id.itemlist);

        //Se o feed for NULL atualiza a Tela
        if (comboitems == null)
        {
            feedtitle.setText("O Feed RSS não está disponível");
            return;
        }

        feedtitle.setText(nome);

        ArrayAdapter<RSSItem> adapter = new
                ArrayAdapter<RSSItem>(this,android.R.layout.
                simple_list_item_1,comboitems);

        itemlist.setAdapter(adapter);

        itemlist.setSelection(0);

        itemlist.setOnItemClickListener(this);
    }

    public void onItemClick(AdapterView parent, View v, int position, long id)
    {
        Log.i(tag, "item clicked! [" + comboitems.get(position).getTitle() + "]");

        Intent itemintent = new Intent(this,ShowDescription.class);

        Bundle b = new Bundle();
        b.putString("title", comboitems.get(position).getTitle());
        b.putString("description", comboitems.get(position).getDescription());
        b.putString("link", comboitems.get(position).getLink());
        b.putString("pubdate", comboitems.get(position).getPubDate());

        itemintent.putExtra("android.intent.extra.INTENT", b);

        startActivityForResult(itemintent, 0);
    }
}

